// MinShuoCourseController.java
package com.hxci.liminshuo.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxci.liminshuo.pojo.MinShuoCourse;
import com.hxci.liminshuo.servcie.MinShuoCorseService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("minshuo/course")
public class MinShuoCourseController {
    @Autowired
    MinShuoCorseService service;

    @RequestMapping("view")
    public String view(){
        return "liminshuo/index";
    }

    @ResponseBody
    @RequestMapping("query")
    public List<MinShuoCourse> query(){
        System.out.println("==========");
        List<MinShuoCourse> list = service.query();
        return list;
    }

    @ResponseBody
    @RequestMapping("queryByCondition")
    public List<MinShuoCourse> queryByCondition(@RequestParam("keyword") String keyword){
        List<MinShuoCourse> list = service.queryByCondition(keyword);
        return list;
    }
    // MinShuoCourseController.java
    @ResponseBody
    @RequestMapping("add")
    public int add(MinShuoCourse course){
        return service.insert(course);
    }

    @ResponseBody
    @RequestMapping("getById")
    public MinShuoCourse getById(@RequestParam("id") Integer id){
        return service.selectById(id);
    }

    @ResponseBody
    @RequestMapping("update")
    public int update(MinShuoCourse course){
        return service.update(course);
    }


    @ResponseBody
    @RequestMapping("delete")
    public int delete(@RequestParam("id") Integer id){
        return service.deleteById(id);
    }
    @ResponseBody
    @RequestMapping("queryByPage")
    public Map<String, Object> queryByPage(@RequestParam(defaultValue = "1") int pageNum,
                                           @RequestParam(defaultValue = "10") int pageSize) {
        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);
        List<MinShuoCourse> list = service.query();
        PageInfo<MinShuoCourse> pageInfo = new PageInfo<>(list);

        Map<String, Object> result = new HashMap<>();
        result.put("courses", list);
        result.put("total", pageInfo.getTotal());
        result.put("pageNum", pageInfo.getPageNum());
        result.put("pageSize", pageInfo.getPageSize());
        result.put("pages", pageInfo.getPages());

        return result;
    }
    // MinShuoCourseController.java
    @ResponseBody
    @RequestMapping("statistics")
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();

        // 获取总课程数
        List<MinShuoCourse> allCourses = service.query();
        stats.put("totalCourses", allCourses.size());

        // 按教师统计课程数
        Map<String, Long> coursesByTeacher = allCourses.stream()
                .collect(Collectors.groupingBy(MinShuoCourse::getTea, Collectors.counting()));
        stats.put("coursesByTeacher", coursesByTeacher);

        // 关键词统计
        Map<String, Integer> keywordCount = new HashMap<>();
        for (MinShuoCourse course : allCourses) {
            String[] keywords = (course.getCname() + " " + course.getMark()).toLowerCase().split("\\s+");
            for (String keyword : keywords) {
                if (keyword.length() > 2) { // 只统计长度大于2的关键词
                    keywordCount.put(keyword, keywordCount.getOrDefault(keyword, 0) + 1);
                }
            }
        }

        // 获取最常见的5个关键词
        List<Map.Entry<String, Integer>> topKeywords = keywordCount.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .limit(5)
                .collect(Collectors.toList());

        stats.put("topKeywords", topKeywords);

        return stats;
    }
    // MinShuoCourseController.java
    @RequestMapping("export")
    public void exportCourses(HttpServletResponse response) throws IOException {
        List<MinShuoCourse> courses = service.query();

        response.setContentType("text/csv;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"courses.csv\"");

        try (PrintWriter writer = response.getWriter()) {
            // 写入CSV头部
            writer.println("ID,课程名称,简介,教师");

            // 写入数据
            for (MinShuoCourse course : courses) {
                writer.printf("%d,\"%s\",\"%s\",\"%s\"%n",
                        course.getId(),
                        course.getCname(),
                        course.getMark(),
                        course.getTea());
            }
        }
    }
    // MinShuoCourseController.java
    @ResponseBody
    @RequestMapping("batchDelete")
    public int batchDelete(@RequestParam("ids") List<Integer> ids) {
        int count = 0;
        for (Integer id : ids) {
            count += service.deleteById(id);
        }
        return count;
    }



}

